package edu.spec.ycloud.controller;

import edu.spec.ycloud.service.OutboundCallback;
import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

/**
 * Author       : MadFrog
 * Date         : 2018/8/20 18:29
 * Description  :
 */
@Controller
@RequestMapping("/door")
public class DoorController {

    @Resource
    private MqttPahoMessageHandler outboundHandler;
    @Resource
    private DefaultMqttPahoClientFactory clientFactory;

    // 消息发布
    @RequestMapping(value="/open")
    public String sendMessage(){
//        Message<String> message = MessageBuilder
//                .withPayload("open the door please!")
//                .setHeader(MqttHeaders.TOPIC, "ycloud").build();
//        outboundHandler.handleMessage(message);
//        System.out.println("发送成功!");
        try {

            //从clientFactory取client，配置的username,password等没有生效
            IMqttClient client = clientFactory.getClientInstance("tcp://www.yyjsx.xyz:61613", "java_center");

            client.setCallback(new OutboundCallback());
            client.connect();
            MqttMessage message = new MqttMessage("ertwersfasdfasddfas".getBytes());
            client.publish("ycloud->chrome", message);
            client.disconnect();

        } catch (MqttException e) {
            e.printStackTrace();
        }
        return "index";
    }

}
